package teamwork.pc.dao;
import static org.seasar.extension.jdbc.operation.Operations.eq;
import static teamwork.pc.entity.Names.staff;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.seasar.framework.util.StringUtil;

import teamwork.pc.entity.Staff;

/**
 * {@link Staff}
 * @author CUONG
 *
 */
public class StaffDao extends AbstractDao<Staff>{
    /**
     * return certain conditions entity
     * @param email
     * @param password
     * @return
     */
    public Staff findByEmailAndPassword(String email, String rawPassword){
        if(StringUtil.isEmpty(email) || StringUtil.isEmpty(rawPassword))
        {
            return null;
        }
        //String scrambledPassword  = this.rawPasswordToScrambled(rawPassword);
        return select()
                .where(
                        eq(staff().email(), email),
                        eq(staff().password(), rawPassword)
                        )
                        .getSingleResult();
    }
    /**
     * Make scrambled password from raw password
     * @param rawPassword
     * @return
     */
    public String rawPasswordToScrambled(String rawPassword){
        MessageDigest md = null;
        final String key = "ASDFXCFHYKF8289AFVSMMNV221SQTT";
        try {
            md = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException();
        }
        md.reset();
        md.update((key + rawPassword).getBytes());
        byte[] digest = md.digest();
        StringBuilder sb = new StringBuilder();
        for(byte b : digest){
            sb.append(Integer.toHexString((b >> 4) & 0x0F));
            sb.append(Integer.toHexString(b & 0x0F));
        }
        return sb.toString();
    }
}
